﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Web.Security;

namespace TireService.Web.UserControls
{
    public partial class ucMoveTireSet : System.Web.UI.UserControl
    {

        #region Public Properties

        public int TireSetId
        {
            get
            {
                if (ViewState["_tiresetid"] != null)
                    return (int)ViewState["_tiresetid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_tiresetid"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void LoadMoveToCargoRoom(int TireSetId)
        {
            if (TireSetId != 0)
            {
                // Instantiate datalayer
                TireServiceDB db = new TireServiceDB();

                TireSet tireset = db.GetTireSet(TireSetId);
                
                if (tireset != null)
                {
                    this.TireSetId = TireSetId;
                }
                else
                {
                    // Error
                    throw new ArgumentException("Hjulsæt ikke fundet");
                }
            }
            else
            {
                // Error
                throw new ArgumentException("Hjulsæt ikke fundet");
            }
        }

        protected void SelectedMoveTypeChanged(int TireSetId, int MoveTypeId)
        {
            // Instantiate datalayer
            TireServiceDB db = new TireServiceDB();

            TireSet tireset = db.GetTireSet(TireSetId);

            if (tireset.TireSetStatusId != (int)Shared.TireSetStatus.OnStock)
            {
                // Error
                throw new ArgumentException("Hjulsæt ligger ikke på lager");
            }

            if (MoveTypeId == 0)
            {
                // Move tireset to other cargoroom
                pMoveCargoRoom.Visible = true;
                pMoveContainer.Visible = false;

                lblCurrentCargoRoomValue.Text = db.GetContainerCargoRoomNumber(Convert.ToInt32(tireset.ContainerCargoRoomId)).ToString();

                // Refresh dropdown with cargorooms
                ShowOccupiedCargoRoom(db, tireset);
            }

            if (MoveTypeId == 1)
            {
                // Move tireset to other container
                pMoveCargoRoom.Visible = false;
                pMoveContainer.Visible = true;

                string CurrentContainer = db.GetContainer(db.GetContainerIdForCargoRoom(Convert.ToInt32(tireset.ContainerCargoRoomId))).ContainerNumber.ToString();

                lblCurrentContainerValue.Text = CurrentContainer;

                ddlContainer.TextField = "ContainerNumber";
                ddlContainer.ValueField = "ContainerId";
                ddlContainer.DataSource = db.GetContainers().Where(p => p.ContainerNumber != CurrentContainer).ToList();
                ddlContainer.DataBind();
            }

            //if (Convert.ToInt32(rbtnMoveType.Value) == 2)
            //{
            //    // Move tireset out of container - delivered back to customer    
            //}
        }

        protected void ShowOccupiedCargoRoom(TireServiceDB db, TireSet tireset)
        {
            if (tireset.TireSetStatusId != (int)Shared.TireSetStatus.OnStock)
            {
                // Error
                throw new ArgumentException("Hjulsæt ligger ikke på lager");
            }

            if (cbShowOccupiedCargoRoom.Checked)
            {
                // Rebind cargoroom dropdownlist and include all cargorooms (also occupied)
                BindCargoRoomDropdownList(db, true, db.GetContainerIdForCargoRoom(Convert.ToInt32(tireset.ContainerCargoRoomId)));
            }
            else
            {
                // Rebind cargoroom dropdownlist and only include available cargorooms
                BindCargoRoomDropdownList(db, false, db.GetContainerIdForCargoRoom(Convert.ToInt32(tireset.ContainerCargoRoomId)));
            }
        }

        protected void BindCargoRoomDropdownList(TireServiceDB db, bool IncludeAllCargoRooms, int ContainerId)
        {
            ddlCargoRoom.TextField = "CargoRoomNumber";
            ddlCargoRoom.ValueField = "ContainerCargoRoomId";
            if (IncludeAllCargoRooms)
            {
                ddlCargoRoom.DataSource = db.GetContainerCargoRooms(ContainerId);
            }
            else
            {
                ddlCargoRoom.DataSource = db.GetContainerCargoRoomTireSetViews(ContainerId).Where(p => p.TireSetId == null).OrderBy(p => p.CargoRoomNumber).ToList();
            }
            ddlCargoRoom.DataBind();
        }

        protected void SelectedContainerChanged(int ContainerId)
        {
            // Instantiate datalayer
            TireServiceDB db = new TireServiceDB();

            ddlContainerCargoRoom.TextField = "CargoRoomNumber";
            ddlContainerCargoRoom.ValueField = "ContainerCargoRoomId";
            ddlContainerCargoRoom.DataSource = db.GetContainerCargoRoomTireSetViews(ContainerId).Where(p => p.TireSetId == null).OrderBy(p => p.CargoRoomNumber).ToList(); 
            ddlContainerCargoRoom.DataBind();
        }

        protected void callbackMoveTireSetPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            // Get CallBackAction
            string[] CallBackAction = e.Parameter.Split('|');

            if (CallBackAction[0] == "NoAction")
            {
                LoadMoveToCargoRoom(Convert.ToInt32(CallBackAction[1]));
            }

            if (CallBackAction[0] == "SelectedMoveTypeChanged")
            {
                SelectedMoveTypeChanged(Convert.ToInt32(CallBackAction[1]), Convert.ToInt32(CallBackAction[2]));
            }

            if (CallBackAction[0] == "ShowOccupiedCargoRoom")
	        {
                SelectedMoveTypeChanged(Convert.ToInt32(CallBackAction[1]), Convert.ToInt32(rbtnMoveType.SelectedItem.Value));
	        }

            if (CallBackAction[0] == "SelectedContainerChanged")
            {
                SelectedMoveTypeChanged(Convert.ToInt32(CallBackAction[1]), Convert.ToInt32(rbtnMoveType.SelectedItem.Value));

                SelectedContainerChanged(Convert.ToInt32(CallBackAction[2]));
            }
        }

        /// <summary>
        /// Callback function that moves tireset to new cargoroom
        /// </summary>
        protected void callMoveCargoRoom_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values from client
                string[] param = e.Parameter.Split('|');

                int TireSetId = Convert.ToInt32(param[0]);
                int NewContainerCargoRoomId = Convert.ToInt32(param[1]);

                // Instantiate datalayer
                TireServiceDB db = new TireServiceDB();

                TireSet tireset = db.GetTireSet(TireSetId);

                if (tireset.TireSetStatusId != (int)Shared.TireSetStatus.OnStock)
                {
                    // Error
                    throw new ArgumentException("Hjulsæt ligger ikke på lager");
                }

                // Create tiresetlog for tireset
                TireSetLogBLL bll = new TireSetLogBLL();

                // Check if selected containercargoroom is already used
                TireSet TireSetOccupying = db.TireSets.SingleOrDefault(p => p.ContainerCargoRoomId == NewContainerCargoRoomId);

                int containercargoroomid = Convert.ToInt32(tireset.ContainerCargoRoomId);

                if (TireSetOccupying == null)
                {
                    // No tireset is occupying the cargoroom already

                    // Update tireset
                    tireset.ContainerCargoRoomId = NewContainerCargoRoomId;

                    // Create log
                    bll.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, NewContainerCargoRoomId);
                }
                else
                {
                    // Other tireset occupy cargoroom - move around

                    // Reset occupying tireset cargoroom
                    TireSetOccupying.ContainerCargoRoomId = null;

                    // Update tireset
                    tireset.ContainerCargoRoomId = NewContainerCargoRoomId;

                    // Create log
                    bll.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, NewContainerCargoRoomId);

                    // Give occupying tireset new cargoroom
                    TireSetOccupying.ContainerCargoRoomId = containercargoroomid;

                    // Create log for occupying tireset
                    bll.CreateTireSetLog(db, TireSetOccupying, DateTime.Now, TireSetOccupying.TireSetStatusId, TireSetOccupying.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, TireSetOccupying.ContainerCargoRoomId);
                }

                // Commit changes to database
                db.SubmitChanges();

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }

        /// <summary>
        /// Callback function that moves tireset to new container
        /// </summary>
        protected void callMoveContainer_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values from client
                string[] param = e.Parameter.Split('|');

                int TireSetId = Convert.ToInt32(param[0]);
                int NewContainerId = Convert.ToInt32(param[1]);
                int NewContainerCargoRoomId = Convert.ToInt32(param[2]);

                // Instantiate datalayer
                TireServiceDB db = new TireServiceDB();

                TireSet tireset = db.GetTireSet(TireSetId);

                if (tireset.TireSetStatusId != (int)Shared.TireSetStatus.OnStock)
                {
                    // Error
                    throw new ArgumentException("Hjulsæt ligger ikke på lager");
                }

                // Create tiresetlog for tireset
                TireSetLogBLL bll = new TireSetLogBLL();

                // Check if selected containercargoroom is already used
                TireSet TireSetOccupying = db.TireSets.SingleOrDefault(p => p.ContainerCargoRoomId == NewContainerCargoRoomId);

                int containercargoroomid = Convert.ToInt32(tireset.ContainerCargoRoomId);

                if (TireSetOccupying == null)
                {
                    // No tireset is occupying the cargoroom already

                    // Update tireset
                    tireset.ContainerCargoRoomId = NewContainerCargoRoomId;

                    // Create log
                    bll.CreateTireSetLog(db, tireset, DateTime.Now, tireset.TireSetStatusId, tireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lager lokation", null, null, null, null, NewContainerCargoRoomId);
                }
                else
                {
                    // cargoroom already occupied - raise exception

                    // Error
                    throw new ArgumentException("Lagerplads på nyt lager allerede optaget");
                }

                // Commit changes to database
                db.SubmitChanges();

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException("Fejl opstod: " + ex.Message);
            }
        }
    }
}